var ns, bmLocation,trans,WXPhotoPicker;
app = new Vue({
    el: '#app',
    data: {
        newform: {
            EncriptID: '',
            PlanType: 4,
            PlanTypeDesc: '环境保洁',
            EventRegionID: 0,
            RegionName: '',
            ProjectID: 0,
            ProjectName: '',
            CheckTime: '',
            InChargeManName: '',
            ProcessContent: '',
            CheckStatus: 1,
            TaskCompleteContent: '',
            GPSLocation: '',
            IsAllowUpload: false,
            EventTypeID: 0,
            EventTypeDesc: '',
            StandardID: 0,
            StandardName: '',
        },
        imglist: [],
        ProjectList: [],
        standardlist: [],
        maxuploadcount: CONFIG.maxuploadcount,
        EventTypeList: [{
            ID: '1',
            Name: '环境保洁'
        }, {
            ID: '2',
            Name: '绿化养护'
        }, {
            ID: '3',
            Name: '四害消杀'
        }, {
            ID: '4',
            Name: '垃圾清运'
        }, {
            ID: '5',
            Name: '其他事件'
        },],
        IsAllowWatermark:false,
        //首页-手动添加
        IsHome:false,
        RegionID:0,
    },
    methods: {
        do_choose_device: function () {
            var that = this;
            if (that.IsHome) {
                return;
            }
            if (that.newform.ProjectID == '') {
                api.toast({
                    msg: '请优先选择所属项目',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            } else {
                ns.openWin('bjlh_regionlist_frm', '选择保洁区域', {
                    projectid: that.newform.ProjectID,
                    typeid: that.newform.EventTypeID
                });

            }
        },
        do_save: function () {
            var that = this;
            if (that.newform.EventTypeID <= 0) {
                api.toast({
                    msg: '请选择任务类型',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.EventRegionID <= 0) {
                api.toast({
                    msg: '请选择保洁区域',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.IsAllowUpload && that.imglist.length == 0) {
                api.toast({
                    msg: '请上传图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            that.do_save_process(0);
        },
        do_save_process: function (ServiceStatus) {
            var that = this;
            //alert(that.newform.PlanType);
            var options = {};
            options.action = "saveequipmenttaskdevicedata";
            options.CheckStatus = 1;
            options.EventTypeID = that.newform.EventTypeID;
            options.EventRegionID = that.newform.EventRegionID;
            options.PlanType = that.newform.PlanType;
            options.GPSLocation = that.newform.GPSLocation;
            options.TaskCompleteContent = that.newform.TaskCompleteContent;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    api.sendEvent({
                        name: 'reloadhomedetail',
                    });
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    }); 
                    setTimeout(function () {
                        api.closeWin();
                    }, 500)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                if (that.IsAllowWatermark) {
                    that.upload_choose_picture();
                }
                else {
                    that.choose_picture_start();
                }
            })
        },
        choose_picture_start:function(){
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function(ret, err) {
                //拍照
                if(ret.buttonIndex==1){ 
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if(ret.buttonIndex==2){
                    that.choose_picture_album();
                    return;
                } 
                //取消 
                else{
                    return false;  
                }  
            });
        },
        choose_picture_album:function(){
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type:'image',
            }, function(ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.imglist.push({
                                ID: 0,
                                url: item.path,
                                thumbPath: item.path,
                                isupload: true
                            });
                        });
                    }
                }
            });
        },
        remove_img: function (index,item) {
            var that = this;
            that.imglist.splice(index, 1);
            if (item.ID > 0) {
                that.do_remove_uploadimg(item);
            }
        },
        do_remove_uploadimg: function (item) {
            var that = this;
            var options = {
                action: 'doremoveproductimg',
                ID: item.ID,
            }
            ns.post(options, function (succeed, data, err) { });
        },
        StartBmap: function () {
            var that = this;
            ns.confirmPer('location', function () {
                that.StartLocation();
            })
        },
        StartLocation: function () {
            var that = this;
            var num = 0; //次数
            that.newform.GPSLocation = '';
            bmLocation.stopLocation();
            bmLocation.singleLocation({
                reGeocode: true,
                netWorkState: true
            }, function (ret) {
                // console.log(JSON.stringify(ret));
                if (ret.status) {
                    var locationDescribe=ns.DealLocationDescribe(ret.reGeo.locationDescribe);
                    that.newform.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        ret.reGeo.district + ret.reGeo.street + ret.reGeo.streetNumber + locationDescribe;
                        // if (ret.reGeo.poiList != undefined && ret.reGeo.poiList.length > 0) {
                        //     that.newform.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        //         ret.reGeo.district + ret.reGeo.street + ret.reGeo.poiList[0].name;
                        // }
                }
            });
        },
        do_selectProject: function () {
            var that = this;
            that.newform.RegionName = '';
        },
        configManager: function () {
            bmLocation.configManager({
                // accuracy: 'hight_accuracy',
                filter: 1,
                activityType: 'automotiveNavigation',
                coordinateType: 'BMK09LL',
                locationTimeout: 10,
                reGeocodeTimeout: 10
            });
        },
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        do_choose_project: function () {
            var that = this;
            ns.openWin('chooseprojectlist_frm', '选择项目', {
                projectlevel: 1,
            });
        },
        get_select_project: function (data) {
            var that = this;
            that.newform.ProjectID = data.projectid;
            that.newform.ProjectName = data.name;
            that.getIsAllowWatermark();//获取是否只调用相机权限
        },
        get_project_list: function () {
            var that = this;
            var options = {
                action: 'getmytopprojectlist'
            };
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.ProjectList = data.list;
                    that.newform.ProjectID = that.ProjectList[0].ID;
                    that.newform.ProjectName = data.list[0].Name;
                    that.initPicker();//加载下拉列表数据
                    that.getIsAllowWatermark();//获取是否只调用相机权限
                }
            });
        },
        get_standard_data: function () {
            var that = this;
            if (that.newform.EncriptID == '') {
                return;
            }
            var options = {};
            options.action = "getdevicestandardlist";
            options.EventRegionID = that.newform.EventRegionID;
            options.EncriptID = that.newform.EncriptID;
            options.PlanType = 4;
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    //alert(JSON.stringify(data));
                    that.standardlist = data.list;
                    that.newform.CheckTime = data.CheckTime;
                    that.newform.InChargeManName = data.InChargeManName;
                    if (that.newform.EncriptID != '') {
                        that.newform.EventRegionID = data.EventRegionID;
                        that.newform.RegionName = data.RegionName;
                        that.newform.ProjectID = data.ProjectID;
                        that.newform.ProjectName = data.ProjectName;
                        that.newform.EventTypeID = data.EventID;
                        app.newform.StandardID = data.StandardID;
                        app.newform.StandardName = data.StandardName;
                        that.getIsAllowWatermark();//获取是否只调用相机权限
                    }
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    // 选择项目
                    var pickerProject = new $.PopPicker({
                        layer: 1,
                        fileID: 'ID',
                        fileName: 'Name',
                    });
                    var projectData = _this.ProjectList || [];
                    pickerProject.setData(projectData);
                    var showProjectPickerButton = doc.getElementById('chooseproject');
                    showProjectPickerButton.addEventListener('click', function (event) {
                        pickerProject.show(function (items) {
                            if(_this.newform.ProjectID!= items[0].value){   
                                _this.newform.EventRegionID = 0;
                                _this.newform.RegionName = '';
                                _this.newform.IsAllowUpload = false;
                                _this.newform.StandardID = 0;
                                _this.newform.StandardName = '';
                             }
                            _this.newform.ProjectID = items[0].value;
                            _this.newform.ProjectName = items[0].text;
                            _this.getIsAllowWatermark();//获取是否只调用相机权限
                            //返回 false 可以阻止选择框的关闭
                            //return false;
                        });
                    }, false);

                    // 选择工作类型
                    var pickerEventType = new $.PopPicker({
                        layer: 1,
                        fileID: 'ID',
                        fileName: 'Name',
                    });
                    var eventtypeData = _this.EventTypeList || [];
                    pickerEventType.setData(eventtypeData);
                    var showEventPickerButton = doc.getElementById('chooseeventtype');
                    showEventPickerButton.addEventListener('click', function (event) {
                        pickerEventType.show(function (items) {
                            _this.newform.EventTypeID = items[0].value;
                            _this.newform.EventTypeDesc = items[0].text;
                            //返回 false 可以阻止选择框的关闭
                            //return false;
                        });
                    }, false);

                });
            })(mui, document);
        },
        //获取是否只调用相机权限
        getIsAllowWatermark:function(){
            var that = this;
            if (!that.newform.ProjectID) {
                return;
            }
            var options = {
                action: 'getplanparam',
                ProjectID:that.newform.ProjectID,
                ConfigKey:'BJPhotoUse'
            };
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.IsAllowWatermark = data.type == 2 ? true : false;
                }
            });
        },
        // 系统只调用相机 并添加水印
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: that.IsAllowWatermark?false:true,
            }, function(ret, err) {
                if (ret&&ret.data) {
                    if (that.IsAllowWatermark) {
                        that.waterMark(ret.data);
                        return;
                    }
                    else {
                        that.imglist.push({
                            ID: 0,
                            url: ret.data,
                            thumbPath: ret.data,
                            isupload: true
                        });
                    }
                } 
            });
        },
        waterMark: function (imagePath) {
            var that = this;
            if(!imagePath){
                api.toast({
                    msg: '图片地址为空',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            } 
            var imageName =imagePath.split('/').pop(); //获取图片名称
            var dateTime = moment().format('YYYY-MM-DD HH:mm:ss');
            // 调用生成水印方法  返回Base64图片格式
            ns.setWatermark(imagePath, '环境保洁水印', dateTime, that.newform.GPSLocation).then((value) => {
                var base64Str=value;
                if (base64Str) {
                    //Base64图片 转jpg、png格式
                    trans.saveImage({
                        base64Str: base64Str,
                        // album:true,
                        imgPath: "fs://watermark/",
                        imgName: imageName
                    }, function (ret, err) {
                        if (ret.status) {
                            var newImagePath=api.fsDir + '/'+'watermark'+'/'+imageName;
                            that.imglist.push({
                                ID: 0,
                                url:newImagePath,
                                thumbPath: newImagePath,
                                isupload: true
                            });
                            //水印图片-保存到相册
                            api.saveMediaToAlbum({
                                path: 'fs://watermark/'+imageName
                            }, function(ret, err) {
                            });
                        } else {
                            api.toast({
                                msg: '水印图片保存本地失败！',
                                duration: 2000,
                                location: 'bottom'
                            });
                            return;
                        }
                    });
                }else{
                    // api.toast({
                    //     msg: '生成水印失败！',
                    //     duration: 2000,
                    //     location: 'bottom'
                    // });
                    that.imglist.push({
                        ID: 0,
                        url: imagePath,
                        thumbPath: imagePath,
                        isupload: true
                    });
                    return;
                }   
            }) 
        },
        getHomeDetail(){
            var that=this;
            if(that.RegionID<=0){
                return;
            }
            var username = api.getPrefs({
                sync: true,
                key: 'username'
            });
            var options = {}; 
            options.ID = that.RegionID;   
            options.EncriptID ="";   
            options.action = "geteventregiondetail";
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    if(data.status){
                        var form = data.data;
                        app.newform.EventRegionID = form.ID;
                        app.newform.RegionName = form.RegionName;
                        app.newform.ProjectID = form.ProjectID;
                        app.newform.ProjectName = form.ProjectName;
                        app.newform.EventTypeID=form.Event;
                        app.newform.EventTypeDesc=form.EventDesc;
                        app.newform.StandardName=form.StandardContent;
                        app.newform.CheckTime = moment().format('YYYY-MM-DD HH:mm');      
                        app.newform.InChargeManName = username;
                    }
                } 
            })
        },
    }
});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    bmLocation = api.require('bmLocation');
    trans = api.require('trans');
    WXPhotoPicker = api.require('WXPhotoPicker');
    var username = api.getPrefs({
        sync: true,
        key: 'username'
    });
    app.newform.EncriptID = api.pageParam.EncriptID || '';
    app.newform.EventTypeID = app.EventTypeList[0].ID;
    app.newform.EventTypeDesc = app.EventTypeList[0].Name;

    //首页跳转
    app.IsHome= api.pageParam.IsHome || false;
    app.RegionID=api.pageParam.RegionID || 0;
    if(app.IsHome){
        app.getIsAllowWatermark();//获取是否只调用相机权限
        app.getHomeDetail();
    }
    else{
        app.get_project_list();
    }
   
    setTimeout(function () {
        if (app.newform.EncriptID != '') {
            app.get_standard_data();
        }
    }, 500)
    setTimeout(function () {
        app.configManager();
        app.StartBmap();
    }, 1000)
    api.addEventListener({
        name: 'do_choose_region_done'
    }, function (ret, err) {
        app.newform.EventRegionID = ret.value.id;
        app.newform.RegionName = ret.value.name;
        app.newform.ProjectName = ret.value.projectname;
        app.newform.IsAllowUpload = ret.value.IsAllowUpload;
        app.newform.StandardID = ret.value.StandardID;
        app.newform.StandardName = ret.value.StandardName;
        app.newform.CheckTime = moment().format('YYYY-MM-DD HH:mm');    
        app.newform.InChargeManName = username;
    });
    app.get_select_project(api.pageParam);
    api.addEventListener({
        name: 'do_choose_project_complete'
    }, function (ret) {
        app.get_select_project(ret.value);
    })
    bmLocation.setAgreePrivacy({
        agree: true
    });
};
